import platform
import subprocess
import time
import os

DEBUG_FEATURE_FLAG = False
DICT_DIR = 'dict;dict' if platform.system() == 'Windows' else 'dict:dict'


def builder():
    print('[INFO] Checking System State...', end='')
    if platform.system() == 'Darwin' or platform.system() == 'Windows':
        print('ok.')
        print('正在锁定代码...', end='')
        source = open('main.py', 'r', encoding='utf-8').readlines()
        f = open('Wordle-Game-Python.py', 'w', encoding='utf-8')
        f.writelines(source)
        f.close()
        print('ok.')
        print('[INFO] Downloading requirements', end='')
        p = subprocess.Popen(
            ['pip3', 'install', '-r', 'requirements.txt', '-i',
             'https://pypi.tuna.tsinghua.edu.cn/simple/'], stdout=subprocess.DEVNULL)
        while True:
            if p.poll() is None:
                time.sleep(0.1)
                print('.', end='')
                continue
            if p.poll() != 0:
                print('[ERROR] Failed to install requirements!')
            break
        print('ok.')
        print('[INFO] Building project', end='')
        if DEBUG_FEATURE_FLAG:
            p = subprocess.Popen(
                ['pyinstaller', '-y', '-F', 'Wordle-Game-Python.py',
                 '--add-data', DICT_DIR])
        else:
            p = subprocess.Popen(
                ['pyinstaller', '-y',  '-F', '--noconsole', 'Wordle-Game-Python.py',
                 '--add-data', DICT_DIR])
        while True:
            if p.poll() is None:
                time.sleep(0.1)
                print('.', end='')
                continue
            break
        print('ok. See binary file at dist/')
        print('正在清理...', end='')
        os.remove('Wordle-Game-Python.py')
        print('ok.')
    else:
        print('[ERROR] Your platform is not supported yet!')


if __name__ == '__main__':
    builder()
